package com.wjc.file.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.wjc.server.dto.CommonDto;
import com.wjc.server.dto.FileDto;
import com.wjc.server.enums.FileUseEnum;
import com.wjc.server.service.FileService;
import com.wjc.server.util.Base64ToMultipartFile;
import com.wjc.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/admin")
public class OssController {

    private static final Logger LOG= LoggerFactory.getLogger(OssController.class);
    public static final String BUSINESS_NAME = "OSS上传";

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private FileService fileService;

    @Value("${file.domain}")
    private String FILE_DOMAIN;

    @Value("${file.path}")
    private String FILE_PATH;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.ossDomain}")
    private String ossDomain;

    @Value("${oss.bucket}")
    private String bucket;


    @PostMapping("/oss-append")
    public CommonDto upload(@RequestBody FileDto fileDto) throws IOException {
        String use=fileDto.getUse();
        String key =fileDto.getKey();
        String suffix=fileDto.getSuffix();
        String shardBase64=fileDto.getShard();
        MultipartFile shard = Base64ToMultipartFile.base64ToMultipart(shardBase64);
        Integer shardIndex = fileDto.getShardIndex();
        Integer shardSize=fileDto.getShardSize();
        //保存文件到本地
        FileUseEnum fileUseEnum= FileUseEnum.getByCode(use);
        //获取文件后缀,小写
//        Long key = snowFlake.nextId();
        //如果文件夹不存在则创建
        String dir=fileUseEnum.name().toLowerCase();
        //File.separator,根据操作系统不同生成不同的/或\
       //String path=dir+File.separator+key +"." +suffix;
        //生成分片路径,例如: course/wad2123dfa.mp4.1
        String shardpath= new StringBuffer(dir)
                .append(File.separator)
                .append(key)
                .append(".")
                .append(suffix)
                .append(".")
                .append(fileDto.getShardIndex()).toString();

        //生成文件路径,例如: course/wad2123dfa.mp4,不含".1"
        String filepath= new StringBuffer(dir)
                .append("/")
                .append(key)
                .append(".")
                .append(suffix).toString();

        //创建oss实例
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        ObjectMetadata metadata=new ObjectMetadata();
        //指定上传的内容类型
        metadata.setContentType("text/plain");
        // 通过AppendObjectRequest设置多个参数。
        AppendObjectRequest appendObjectRequest = new
                AppendObjectRequest(bucket, filepath, new ByteArrayInputStream(shard.getBytes()),metadata);

        //第一次追加，设置文件的追加位置
        appendObjectRequest.setPosition((long)((shardIndex-1)*shardSize));
        AppendObjectResult appendObjectResult=ossClient.appendObject(appendObjectRequest);
        // 文件的64位CRC值。此值根据ECMA-182标准计算得出。
        System.out.println(appendObjectResult.getObjectCRC());
        System.out.println(JSONObject.toJSONString(appendObjectResult));
        //关闭ossclient
        ossClient.shutdown();

        //保存文件记录
        LOG.info("保存文件记录开始");
        fileDto.setPath(filepath);
        fileService.save(fileDto);
        CommonDto commonDto = new CommonDto<>();
        fileDto.setPath(ossDomain+filepath);
        commonDto.setContent(fileDto);
        return commonDto;
    }


    @PostMapping("/oss-simple")
     public CommonDto fileUpload(@RequestParam MultipartFile file,String use) throws IOException {
        LOG.info("文件上传开始");
        FileUseEnum fileUseEnum=FileUseEnum.getByCode(use);
        Long key=snowFlake.nextId();
        String fileName=file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        String dir= fileUseEnum.name().toLowerCase();
        String path=dir+"/"+key+"."+suffix;

        //创建oss实例
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        PutObjectRequest putObjectRequest=new PutObjectRequest(bucket,path,new ByteArrayInputStream(file.getBytes()));
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        CommonDto commonDto=new CommonDto();
        FileDto fileDto=new FileDto();
        fileDto.setPath(ossDomain+path);
        commonDto.setContent(fileDto);
        return commonDto;
    }




}
